package com.gcloud.mesh.dcs.chain;


import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.dcs.enums.SchedulerJobStatus;
import com.gcloud.mesh.dcs.enums.SchedulerStepStatus;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 检测异步迁移任务状态超时 status = 2 and end_time is null and sync_exec = 0
 */

@Slf4j
@Component
public class MigrationStatusOuttimeSchedule {

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Autowired
    private SchedulerJobDao schedulerJobDao;

    @Scheduled(fixedDelay = 1000 * 60)
    public void doExec() {
        String uuid = UUID.randomUUID().toString();
        try {
            log.info(uuid+"[CheckVMStatusTask] 检测迁移超时任务状态定时器开始【超过12小时未完成】");
            String sql = "select * from dcs_scheduler_steps t " +
                    " where status < 2 and end_time is null " +
                    " and now() >= TIMESTAMPADD(MINUTE, 72*60, begin_time)" +
                    " order by begin_time" +
                    "";
            List<SchedulerStepEntity> stepEntityList = schedulerStepDao.findBySql(sql, SchedulerStepEntity.class);
            if(stepEntityList!=null && !stepEntityList.isEmpty()){
                log.info(uuid+"一共有"+stepEntityList.size()+"个超时任务");
                for (SchedulerStepEntity schedulerStepEntity : stepEntityList) {
                    schedulerStepDao.updateStepStatusById(schedulerStepEntity.getId(),SchedulerStepStatus.FAIL,"执行超时");
                    schedulerJobDao.updateJobStatusById(schedulerStepEntity.getSchedulerJobId(), SchedulerJobStatus.FAIL);

                }
            }else{
                log.info(uuid+"没有需要处理的超时任务");
            }

        }finally {
            log.info(uuid+"[CheckVMStatusTask] 检测迁移超时任务状态定时器结束【超过12小时未完成】");
        }




    }
}
